﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Filter;
using PARK.Consumer.Entity;
using PARK.Consumer.Entitys.Dto.ConsumtimeInterval;
using PARK.Consumer.Interfaces;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using SqlSugar;
using System.Linq;
using System.Threading.Tasks;

namespace PARK.Consumer
{
    /// <summary>
    /// 餐段
    /// </summary>
    [ApiDescriptionSettings(Tag = "Consum", Name = "TimeInterval", Order = 200)]
    [Route("api/consum/[controller]")]
    public class ConsumtimeIntervalService : IConsumMachineService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ConsumtimeIntervalEntity> _consumtimeIntervalRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ConsumtimeIntervalService"/>类型的新实例
        /// </summary>
        public ConsumtimeIntervalService(
            ISqlSugarRepository<ConsumtimeIntervalEntity> consumtimeIntervalRepository,
            IUserManager userManager)
        {
            _consumtimeIntervalRepository = consumtimeIntervalRepository;
            _db = _consumtimeIntervalRepository.Context;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ConsumtimeIntervalEntity>().FirstAsync(p => p.Id == id);
            return entity;
        }
        /// <summary>
		/// 获取列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ConsumtimeIntervalListQuery input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "SortCode" : input.sidx;
                var data = await _db.Queryable<ConsumtimeIntervalEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.TimeIntervalName.Contains(input.keyword))
                    .Select(it => new ConsumtimeIntervalListOutput
                    {
                        Id = it.Id,
                        TimeIntervalName = it.TimeIntervalName,
                        TimeBeg = it.TimeBeg,
                        TimeEnd = it.TimeEnd,
                        CompanyId = it.CompanyId,
                        CompanyName = it.CompanyName
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<ConsumtimeIntervalListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ConsumtimeIntervalCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var et = _db.Queryable<ConsumtimeIntervalEntity>().Where(d => d.TimeIntervalName.Equals(input.TimeIntervalName) && d.CompanyId == userInfo.companyId).ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.COM1004, "所添加餐段已存在！");
                }
                var entity = input.Adapt<ConsumtimeIntervalEntity>();
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                entity.Create();
                var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1000);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ConsumtimeIntervalUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var et = _db.Queryable<ConsumtimeIntervalEntity>().Where(d => d.Id != id && d.TimeIntervalName.Equals(input.TimeIntervalName) && d.CompanyId == userInfo.companyId).ToList().FirstOrDefault();
                if (et != null)
                {
                    throw PARKException.Oh(ErrorCode.COM1004, "所添加餐段已存在！");
                }
                var entity = input.Adapt<ConsumtimeIntervalEntity>();
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                entity.LastModify(id);
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<ConsumtimeIntervalEntity>().FirstAsync(p => p.Id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                var isOk = await _db.Deleteable(entity).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }
        /// <summary>
        /// 获取下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("Selector/{id}")]
        public async Task<dynamic> GetSelector(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var data = await _db.Queryable<ConsumtimeIntervalEntity>().Where(t => t.CompanyId == userInfo.companyId).Select(it => new TimeIntervalSelectorOutput
                {
                    id = it.Id,
                    fullName = it.TimeIntervalName,
                    TimeBeg = it.TimeBeg,
                    TimeEnd = it.TimeEnd
                }).ToListAsync();
                return new { list = data };
            }
            else
                return null;
        }
    }
}
